package operation;

import car.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;


public class AddVehicle implements IOperation {
    Scanner scanner = new Scanner(System.in);

    @Override
    public void work(Cars cars) {
        System.out.println("1. 轿车   2. 客车   3. 卡车");
        System.out.print("请输入你要添加车的类型: ");
        int choice = scanner.nextInt();

        if (choice >= 1 && choice <= 3) {
            addVehicle(cars, choice);
            Vehicle newVehicle = cars.getList(choice).get(cars.getList(choice).size() - 1);
            DBHelper.insertVehicle(newVehicle); // 将新车辆信息添加到数据库
            System.out.println("添加成功!");
        } else {
            System.out.println("输入错误!!!");
        }
    }

    public void addVehicle(Cars cars, int type) {
        switch (type) {
            case 1:
                carAdd(cars);
                break;
            case 2:
                busAdd(cars);
                break;
            case 3:
                trunkAdd(cars);
                break;
            default:
                System.out.println("无效的车辆类型!");
        }
    }

    public void carAdd(Cars cars) {
        System.out.print("请输入轿车的车牌号: ");
        String vehicleId = scanner.next();
        System.out.print("请输入轿车的品牌: ");
        String brand = scanner.next();
        System.out.print("请输入轿车的型号: ");
        String type = scanner.next();
        int perRent = getPerRent();
        Car car = new Car(vehicleId, brand, type, perRent);
        cars.getList(1).add(car);
    }

    public void busAdd(Cars cars) {
        System.out.print("请输入客车的车牌号: ");
        String vehicleId = scanner.next();
        System.out.print("请输入客车的品牌: ");
        String brand = scanner.next();
        System.out.print("请输入客车的型号: ");
        String type = scanner.next();
        int perRent = getPerRent();
        Bus bus = new Bus(vehicleId, brand, type, perRent);
        cars.getList(2).add(bus);
    }

    public void trunkAdd(Cars cars) {
        System.out.print("请输入卡车的车牌号: ");
        String vehicleId = scanner.next();
        System.out.print("请输入卡车的品牌: ");
        String brand = scanner.next();
        System.out.print("请输入卡车的型号: ");
        String type = scanner.next();
        int perRent = getPerRent();
        Trunk trunk = new Trunk(vehicleId, brand, type, perRent);
        cars.getList(3).add(trunk);
    }

    private int getPerRent() {
        int perRent = -1;
        while (perRent < 0) {
            try {
                System.out.print("请输入日租金: ");
                perRent = scanner.nextInt();
                if (perRent < 0) {
                    System.out.println("日租金不能为负数，请重新输入。");
                }
            } catch (Exception e) {
                System.out.println("输入无效，请重新输入日租金。");
                scanner.nextLine(); // 消耗无效的输入
            }
        }
        return perRent;
    }
}

